<template>
  <el-card>
    <el-tabs v-model="activeTab" @tab-change="onTabChange">
      <el-tab-pane v-for="tab in tabs" :key="tab.key" :label="tab.label" :name="tab.key">
        <template v-if="tab.key === 'spider'">
          <!-- 平台商品列表 -->
          <div style="text-align:right; margin-bottom: 12px;">
            <el-button type="primary" @click="showCreatePlatform = true">创建平台</el-button>
          </div>
          <el-form :inline="true" :model="spiderFilter" class="table-toolbar" size="small" style="margin-bottom: 16px;">
            <el-form-item label="商品名称"><el-input v-model="spiderFilter.name" placeholder="请输入商品名称" /></el-form-item>
            <el-form-item label="平台"><el-select v-model="spiderFilter.platform" placeholder="全部" style="width: 140px;"><el-option v-for="p in spiderPlatforms" :key="p" :label="p" :value="p" /></el-select></el-form-item>
            <el-form-item label="状态"><el-select v-model="spiderFilter.status" placeholder="全部" style="width: 120px;"><el-option label="全部" value="" /><el-option label="已上架" value="on" /><el-option label="已下架" value="off" /><el-option label="售罄" value="sold" /></el-select></el-form-item>
            <el-form-item><el-button @click="onSpiderSearch">搜索</el-button></el-form-item>
          </el-form>
          <el-table :data="filteredSpiderGoods" border stripe>
            <el-table-column prop="mainImage" label="主图" width="80">
              <template #default="scope">
                <el-image 
                  :src="scope.row.mainImage" 
                  style="width:60px;height:60px;object-fit:cover;cursor:pointer;" 
                  :preview-src-list="getImagePreviewList(scope.row)"
                  :initial-index="0"
                  fit="cover"
                  preview-teleported
                  @click="handleImageClick(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="platformId" label="平台ID" width="100" />
            <el-table-column prop="originId" label="商品原ID" width="120" />
            <el-table-column prop="name" label="名称" width="180">
              <template #default="scope">
                <a :href="scope.row.baseUrl + scope.row.originId" target="_blank" class="el-link el-link--primary">
                  {{ scope.row.name }}
                </a>
              </template>
            </el-table-column>
            <el-table-column prop="category" label="分类" width="100" />
            <el-table-column prop="brand" label="品牌" width="100" />
            <el-table-column prop="price" label="价格(円)" width="90" />
            <el-table-column prop="stock" label="库存" width="80" />
            <el-table-column prop="status" label="状态" width="90" />
            <el-table-column prop="auditStatus" label="审核状态" width="100">
              <template #default="scope">
                <el-tag :type="getAuditStatusType(scope.row.auditStatus)">{{ formatAuditStatus(scope.row.auditStatus) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="上架时间" width="140" />
            <el-table-column prop="platform" label="所属平台" width="120" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button size="small" type="primary" plain @click="showPriceHistory(scope.row)">价格历史</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="spiderGoodsFilteredTotal > spiderPageSize"
            @size-change="onSpiderPageSizeChange"
            @current-change="onSpiderPageChange"
            :current-page="spiderPage"
            :page-size="spiderPageSize"
            :total="spiderGoodsFilteredTotal"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 16px; text-align: right;"
          />
        </template>
        <template v-else>
          <!-- 自建平台商品列表 -->
          <div style="text-align:right; margin-bottom: 12px;">
            <el-button size="small" @click="onShowRename(tab)">重命名</el-button>
            <el-button size="small" @click="() => moveTab(tab, 'up')">上移</el-button>
            <el-button size="small" @click="() => moveTab(tab, 'down')">下移</el-button>
            <el-button size="small" type="danger" @click="() => onDeletePlatform(tab)">删除平台</el-button>
          </div>
          <el-row :gutter="16" style="margin-bottom: 12px;">
            <el-col :span="6">
              <el-form :inline="true" :model="customFilter" size="small">
                <el-form-item label="商品名称"><el-input v-model="customFilter.name" placeholder="请输入商品名称" /></el-form-item>
                <el-form-item label="批次"><el-select v-model="customFilter.batch" placeholder="全部" style="width:160px;"><el-option v-for="b in customBatches" :key="b" :label="b" :value="b" /></el-select></el-form-item>
                <el-form-item label="状态"><el-select v-model="customFilter.status" placeholder="全部" style="width:120px;"><el-option label="全部" value="" /><el-option label="上架" value="上架" /><el-option label="下架" value="下架" /></el-select></el-form-item>
                <el-form-item><el-button @click="onCustomSearch">搜索</el-button></el-form-item>
              </el-form>
            </el-col>
            <el-col :span="18" style="text-align:right;">
              <el-button type="primary" @click="() => onBatchUp(tab.key)">批量上架</el-button>
              <el-button type="warning" @click="() => onBatchDown(tab.key)">批量下架</el-button>
              <el-button type="success" @click="() => onImport(tab.key)">批量导入</el-button>
              <el-button type="info" @click="() => onAdd(tab.key)">新增商品</el-button>
            </el-col>
          </el-row>
          <el-table :data="getCurrentPlatformGoods(tab.key)" border stripe @selection-change="onSelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column prop="mainImage" label="主图" width="80">
              <template #default="scope">
                <el-image
                  v-if="scope.row.mainImage"
                  :src="getCurrentImage(scope.row)"
                  style="width:60px;height:60px;object-fit:cover;cursor:pointer;"
                  :preview-src-list="getImagePreviewList(scope.row)"
                  :initial-index="0"
                  fit="cover"
                  preview-teleported
                  @mouseenter="handleMouseEnter(scope.row)"
                  @mouseleave="handleMouseLeave(scope.row)"
                  @click="handleImageClick(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="code" label="商品编号" width="100" />
            <el-table-column prop="name" label="商品名称" width="160">
              <template #default="scope">
                <el-link type="primary" @click="showDetail(scope.row)">{{ scope.row.name }}</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格(円)" width="90" />
            <el-table-column prop="freight" label="运费(円)" width="80" />
            <el-table-column prop="photoFee" label="拍照费(円)" width="80" />
            <el-table-column prop="realCount" label="实际件数" width="90" />
            <el-table-column prop="category" label="品目" width="100" />
            <el-table-column prop="brand" label="品牌" width="100" />
            <el-table-column prop="startTime" label="开始时间" width="120" />
            <el-table-column prop="endTime" label="结束时间" width="120" />
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="desc" label="说明" width="120" />
            <el-table-column prop="status" label="状态" width="90" />
            <el-table-column prop="auditStatus" label="审核状态" width="100">
              <template #default="scope">
                <el-tag :type="getAuditStatusType(scope.row.auditStatus)">{{ formatAuditStatus(scope.row.auditStatus) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="batch" label="所属批次" width="120" />
            <el-table-column label="平台类型" width="120">
              <template #default="scope">
                <el-tag 
                  :type="getPlatformTypeTagType(scope.row.platformType || 'normal')" 
                  size="small"
                >
                  {{ getPlatformTypeName(scope.row.platformType || 'normal') }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
              <template #default="scope">
                <el-button size="small" @click="onEdit(scope.row, tab.key)">编辑</el-button>
                <el-button size="small" type="primary" plain @click="showPriceHistory(scope.row)">价格历史</el-button>
                <el-button size="small" type="danger" @click="onDelete(scope.row, tab.key)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="getCurrentPlatformGoodsTotal(tab.key) > customPageSize"
            @size-change="onCustomPageSizeChange"
            @current-change="onCustomPageChange"
            :current-page="customPages[activeTab] || 1"
            :page-size="customPageSize"
            :total="getCurrentPlatformGoodsTotal(tab.key)"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 16px; text-align: right;"
          />
        </template>
      </el-tab-pane>
    </el-tabs>
  </el-card>
  <el-dialog v-model="showCreatePlatform" title="创建平台" width="500px">
    <el-form :model="createPlatformForm" :rules="createPlatformRules" ref="createPlatformFormRef" label-width="100px">
      <el-form-item label="平台名称" prop="name" required>
        <el-input v-model="createPlatformForm.name" placeholder="请输入平台名称" />
      </el-form-item>
      <el-form-item label="平台类型" prop="type" required>
        <el-radio-group v-model="createPlatformForm.type">
          <el-radio label="normal">
            <el-icon><ShoppingCart /></el-icon>
            普通商品平台
          </el-radio>
          <el-radio label="auction">
            <el-icon><Gavel /></el-icon>
            拍卖会平台
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="平台描述" prop="description">
        <el-input 
          v-model="createPlatformForm.description" 
          type="textarea" 
          :rows="3"
          placeholder="请输入平台描述（可选）"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showCreatePlatform = false">取消</el-button>
      <el-button type="primary" @click="onCreatePlatform">创建</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="showRenamePlatform" title="重命名平台" width="400px">
    <el-form>
      <el-form-item label="新名称">
        <el-input v-model="renamePlatformName" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showRenamePlatform = false">取消</el-button>
      <el-button type="primary" @click="onRenamePlatform">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="showAddDialog" :title="editMode ? '编辑商品' : '新增商品'" width="500px">
    <el-form :model="addForm" label-width="90px">
      <el-form-item label="商品名称"><el-input v-model="addForm.name" /></el-form-item>
      <el-form-item label="商品图片">
        <el-upload
          action="#"
          list-type="picture-card"
          :file-list="addForm.images"
          :auto-upload="false"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleImageRemove"
          :on-change="beforeImageUpload"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="价格"><el-input-number v-model="addForm.price" :min="0" /></el-form-item>
      <el-form-item label="运费"><el-input-number v-model="addForm.freight" :min="0" /></el-form-item>
      <el-form-item label="拍照费"><el-input-number v-model="addForm.photoFee" :min="0" /></el-form-item>
      <el-form-item label="实际件数"><el-input-number v-model="addForm.realCount" :min="1" /></el-form-item>
      <el-form-item label="品目"><el-input v-model="addForm.category" /></el-form-item>
      <el-form-item label="品牌"><el-input v-model="addForm.brand" /></el-form-item>
      <!-- 拍卖会平台专用字段 -->
      <template v-if="isAuctionPlatform">
        <el-form-item label="开始时间" required>
          <el-date-picker v-model="addForm.startTime" type="date" placeholder="选择开始日期" />
        </el-form-item>
        <el-form-item label="结束时间" required>
          <el-date-picker v-model="addForm.endTime" type="date" placeholder="选择结束日期" />
        </el-form-item>
      </template>
      <el-form-item label="数量"><el-input-number v-model="addForm.quantity" :min="1" /></el-form-item>
      <el-form-item label="说明"><el-input v-model="addForm.desc" /></el-form-item>
      <el-form-item label="状态"><el-select v-model="addForm.status"><el-option label="上架" value="上架" /><el-option label="下架" value="下架" /></el-select></el-form-item>
      <!-- 所属批次字段 - 只在添加批次时显示 -->
      <el-form-item v-if="showBatchField" label="所属批次">
        <el-select v-model="addForm.batch" placeholder="请选择批次">
          <el-option v-for="b in batchOptions" :key="b" :label="b" :value="b" />
        </el-select>
      </el-form-item>
      
      <!-- 添加批次按钮 -->
      <el-form-item v-if="!showBatchField" label="批次管理">
        <el-button type="primary" size="small" @click="showBatchField = true">
          <el-icon><Plus /></el-icon>
          添加所属批次
        </el-button>
      </el-form-item>
      
      <el-form-item label="自定义字段">
        <div v-for="(field, idx) in addForm.customFields" :key="idx" style="display:flex;align-items:center;margin-bottom:4px;">
          <el-input v-model="field.key" placeholder="字段名" style="width:100px;margin-right:8px;" />
          <el-input v-model="field.value" placeholder="字段值" style="width:140px;margin-right:8px;" />
          <el-button type="danger" size="small" @click="removeCustomField(idx)">删除</el-button>
        </div>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addCustomField">添加字段</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="onSaveConfirm">保存并提交审核</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="showPriceHistoryDialog" title="价格变动历史" width="500px">
    <el-timeline>
      <el-timeline-item v-for="(item, index) in currentPriceHistory" :key="index" :timestamp="item.date">
        价格由 {{ item.oldPrice }}円 变为 {{ item.newPrice }}円，操作人：{{ item.operator }}
      </el-timeline-item>
    </el-timeline>
    <template #footer>
      <el-button @click="showPriceHistoryDialog = false">关闭</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="showImportDialog" title="批量导入" width="400px">
    <div style="margin-bottom:16px;">请下载导入模板，按要求填写后上传。</div>
    <el-button type="primary" @click="downloadImportTemplate">下载导入模板</el-button>
    <el-upload style="margin-top:16px;" :show-file-list="false" :before-upload="beforeImportUpload">
      <el-button>选择文件上传</el-button>
    </el-upload>
    <template #footer>
      <el-button @click="showImportDialog = false">关闭</el-button>
    </template>
  </el-dialog>
  <!-- <ProductDetailDialog :product="currentProduct" v-model:visible="detailVisible" v-if="currentProduct" /> -->
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile } from 'element-plus'
import dayjs from 'dayjs'
import * as XLSX from 'xlsx'
// import ProductDetailDialog from './ProductDetailDialog.vue'

// Tab配置（平台商品Tab为固定，其余为自建平台Tab）
const tabs = ref([
  { key: 'spider', label: '平台商品', fixed: true },
  { key: 'jaa', label: 'JAA活动商品', fixed: false }
])
let tabIndex = 1 // 用于生成唯一key
const activeTab = ref('spider')
function onTabChange() {
  // 可做Tab切换时的数据刷新
}

// 爬取平台商品mock
const spiderPlatforms = ['煤炉', '雅虎日拍', '雅虎闲置']
const spiderGoods = ref(Array.from({ length: 15 }, (_, i) => ({
  mainImage: `https://dummyimage.com/60x60/${['409eff', '67c23a', 'e6a23c'][i % 3]}/fff&text=${spiderPlatforms[i % 3]}`,
  images: [`https://dummyimage.com/400x400/${['409eff', '67c23a', 'e6a23c'][i % 3]}/fff&text=${spiderPlatforms[i % 3]}-1`],
  platformId: `P${String(i + 1).padStart(3, '0')}`,
  originId: `m${123456789 + i}`,
  name: `${spiderPlatforms[i % 3]}商品${i + 1}`,
  category: ['手办/动漫/高达', '模型/拼装/汽车', '玩具/益智/积木'][i % 3],
  brand: ['BANDAI', 'TAKARA', 'SEGA'][i % 3],
  price: 1200 + i * 50,
  priceHistory: [
    { date: '2024-05-15 08:00', oldPrice: 1100 + i * 50, newPrice: 1150 + i * 50, operator: '爬虫' },
    { date: '2024-06-01 18:20', oldPrice: 1150 + i * 50, newPrice: 1200 + i * 50, operator: '爬虫' },
  ],
  stock: 5 + i,
  status: ['已上架', '已下架', '售罄'][i % 3],
  auditStatus: ['approved', 'pending', 'rejected'][i % 3],
  createdAt: `2024-06-${String(i + 1).padStart(2, '0')}`,
  platform: spiderPlatforms[i % 3],
  baseUrl: ['https://jp.mercari.com/item/', 'https://auctions.yahoo.co.jp/jp/auction/', 'https://paypayfleamarket.yahoo.co.jp/item/'][i % 3]
})))

const spiderFilter = ref({ name: '', platform: '', status: '' })
const spiderPage = ref(1)
const spiderPageSize = ref(10)

const spiderGoodsFilteredTotal = computed(() => {
    return spiderGoods.value.filter(g => {
        if (spiderFilter.value.name && !g.name.includes(spiderFilter.value.name)) return false
        if (spiderFilter.value.platform && g.platform !== spiderFilter.value.platform) return false
        if (spiderFilter.value.status && g.status !== spiderFilter.value.status) return false
        return true
    }).length
})

const filteredSpiderGoods = computed(() => {
  let filtered = spiderGoods.value.filter(g => {
    if (spiderFilter.value.name && !g.name.includes(spiderFilter.value.name)) return false
    if (spiderFilter.value.platform && g.platform !== spiderFilter.value.platform) return false
    if (spiderFilter.value.status && g.status !== spiderFilter.value.status) return false
    return true
  })
  const start = (spiderPage.value - 1) * spiderPageSize.value
  return filtered.slice(start, start + spiderPageSize.value)
})
function onSpiderSearch() {
  spiderPage.value = 1
}
function onSpiderPageSizeChange(val: number) {
  spiderPageSize.value = val
}
function onSpiderPageChange(val: number) {
  spiderPage.value = val
}

// 自建平台商品mock
const customBatches = ['2025-07活动', '2025-08活动']
const customGoods = ref([
  { code: 'JAA001', name: 'JAA商品A', freight: 100, photoFee: 20, realCount: 2, category: '手办', brand: 'BANDAI', startTime: '2025-07-01', endTime: '2025-07-31', quantity: 10, desc: '限时特惠', status: '上架', auditStatus: 'approved', batch: '2025-07活动' }
])
const customFilter = ref({ name: '', batch: '', status: '' })
const customPages = reactive<Record<string, number>>({})
const customPageSize = ref(10)
const filteredCustomGoods = computed(() => {
  return customGoods.value.filter(g => {
    if (customFilter.value.name && !g.name.includes(customFilter.value.name)) return false
    if (customFilter.value.batch && g.batch !== customFilter.value.batch) return false
    return true
  })
})
function onCustomSearch() {
  if (customPages[activeTab.value]) {
    customPages[activeTab.value] = 1
  }
}
function onCustomPageSizeChange(val: number) {
  customPageSize.value = val
}
function onCustomPageChange(val: number) {
  customPages[activeTab.value] = val
}

// 自建平台商品数据结构
function getCurrentPlatformGoodsTotal(tabKey: string) {
  const plat = customPlatforms.value.find(p => p.key === tabKey)
  if (!plat) return 0
  let goods = plat.goods
  // a bit of repeated logic, but necessary
  if (customFilter.value.name) goods = goods.filter(g => g.name.includes(customFilter.value.name))
  if (customFilter.value.batch) goods = goods.filter(g => g.batch === customFilter.value.batch)
  if (customFilter.value.status) goods = goods.filter(g => g.status === customFilter.value.status)
  return goods.length
}

// function getCurrentPlatformGoods(tabKey: string) {
//   const plat = customPlatforms.value.find(p => p.key === tabKey)
//   if (!plat) return []
//   let goods = plat.goods
//   // 搜索筛选
//   if (customFilter.value.name) goods = goods.filter(g => g.name.includes(customFilter.value.name))
//   if (customFilter.value.batch) goods = goods.filter(g => g.batch === customFilter.value.batch)
//   if (customFilter.value.status) goods = goods.filter(g => g.status === customFilter.value.status)

//   if (!customPages[tabKey]) customPages[tabKey] = 1
//   const start = (customPages[tabKey] - 1) * customPageSize.value
//   return goods.slice(start, start + customPageSize.value)
// }

const customPlatforms = ref([
  { 
    key: 'jaa', 
    label: 'JAA活动商品', 
    type: 'normal', // 默认为普通商品平台
    description: 'JAA活动商品平台',
    goods: Array.from({ length: 15 }, (_, i) => ({
      code: `JAA${String(i + 1).padStart(3, '0')}`,
      name: `【JAA】${['万代', 'SEGA', '任天堂'][i % 3]} 商品${i + 1}`,
      mainImage: `https://dummyimage.com/100x100/${['409eff', '67c23a', 'e6a23c'][i % 3]}/fff&text=JAA${i + 1}`,
      images: [`https://dummyimage.com/400x400/${['409eff', '67c23a', 'e6a23c'][i % 3]}/fff&text=JAA${i + 1}-1`],
      price: 1500 + i * 100,
      priceHistory: [
        { date: '2024-05-01 10:00', oldPrice: 1400 + i * 100, newPrice: 1450 + i * 100, operator: '系统' },
        { date: '2024-06-01 12:30', oldPrice: 1450 + i * 100, newPrice: 1500 + i * 100, operator: '管理员' },
      ],
      freight: 50 - i,
      photoFee: 10,
      realCount: 1,
      category: ['手办/模型', '游戏/电玩'][i % 2],
      brand: ['万代', 'SEGA', '任天堂'][i % 3],
      startTime: `2025-07-${String(i + 1).padStart(2, '0')}`,
      endTime: `2025-07-31`,
      quantity: 20 - i,
      desc: `商品描述${i + 1}`,
      status: ['上架', '下架'][i % 2],
      auditStatus: ['approved', 'pending', 'rejected'][i % 3],
      batch: ['2025-07活动', '2025-08活动'][i % 2],
      platformType: 'normal', // 添加平台类型
      customFields: [{ key: '材质', value: 'PVC' }]
    })) 
  }
])

// 创建平台弹窗
const showCreatePlatform = ref(false)
const createPlatformFormRef = ref()
const createPlatformForm = ref({
  name: '',
  type: 'normal', // 默认选择普通商品平台
  description: ''
})

// 创建平台表单验证规则
const createPlatformRules = {
  name: [
    { required: true, message: '请输入平台名称', trigger: 'blur' },
    { min: 2, max: 20, message: '平台名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择平台类型', trigger: 'change' }
  ]
}

function onCreatePlatform() {
  createPlatformFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      const { name, type, description } = createPlatformForm.value
      
      if (tabs.value.some(t => t.label === name)) {
        return ElMessage.warning('平台名称已存在')
      }
      
      tabIndex++
      const key = 'custom_' + tabIndex
      const platformData = { 
        key, 
        label: name, 
        type, 
        description,
        fixed: false 
      }
      
      tabs.value.push(platformData)
      customPlatforms.value.push({ 
        key, 
        label: name, 
        type, 
        description,
        goods: [] 
      })
      
      activeTab.value = key
      showCreatePlatform.value = false
      
      // 重置表单
      createPlatformForm.value = {
        name: '',
        type: 'normal',
        description: ''
      }
      
      ElMessage.success(`成功创建${type === 'normal' ? '普通商品' : '拍卖会'}平台：${name}`)
    }
  })
}

// 删除平台
function onDeletePlatform(tab: { key: string }) {
  const plat = customPlatforms.value.find(p => p.key === tab.key)
  if (!plat) return
  if (plat.goods.length > 0) {
    ElMessage.warning('该平台下已有商品，无法删除')
    return
  }
  ElMessageBox.confirm('确定要删除该平台吗？', '提示', { type: 'warning' }).then(() => {
    tabs.value = tabs.value.filter(t => t.key !== tab.key)
    customPlatforms.value = customPlatforms.value.filter(p => p.key !== tab.key)
    if (activeTab.value === tab.key) activeTab.value = 'spider'
    ElMessage.success('删除成功')
  })
}

// 重命名平台
const showRenamePlatform = ref(false)
const renamePlatformName = ref('')
let renameTabKey = ''
function onShowRename(tab: { key: string, label: string }) {
  renamePlatformName.value = tab.label
  renameTabKey = tab.key
  showRenamePlatform.value = true
}
function onRenamePlatform() {
  const name = renamePlatformName.value.trim()
  if (!name) return ElMessage.warning('请输入新名称')
  if (tabs.value.some(t => t.label === name && t.key !== renameTabKey)) return ElMessage.warning('平台名称已存在')
  const tab = tabs.value.find(t => t.key === renameTabKey)
  if (tab) tab.label = name
  const plat = customPlatforms.value.find(p => p.key === renameTabKey)
  if (plat) plat.label = name
  showRenamePlatform.value = false
  renameTabKey = ''
}

// 顺序调整
function moveTab(tab: { key: string }, dir: 'up' | 'down') {
  const idx = tabs.value.findIndex(t => t.key === tab.key)
  if (idx < 1) return // 不能移动到平台商品Tab前
  const newIdx = dir === 'up' ? idx - 1 : idx + 1
  if (newIdx < 1 || newIdx >= tabs.value.length) return
  const temp = tabs.value[idx]
  tabs.value[idx] = tabs.value[newIdx]
  tabs.value[newIdx] = temp
  // customPlatforms顺序也同步
  const platIdx = customPlatforms.value.findIndex(p => p.key === tab.key)
  const platTemp = customPlatforms.value[platIdx]
  customPlatforms.value[platIdx] = customPlatforms.value[newIdx - 1]
  customPlatforms.value[newIdx - 1] = platTemp
}

// 获取当前平台的商品数据
function getCurrentPlatformGoods(tabKey: string) {
  const plat = customPlatforms.value.find(p => p.key === tabKey)
  if (!plat) return []
  let goods = plat.goods
  // 搜索筛选
  if (customFilter.value.name) goods = goods.filter(g => g.name.includes(customFilter.value.name))
  if (customFilter.value.batch) goods = goods.filter(g => g.batch === customFilter.value.batch)
  if (customFilter.value.status) goods = goods.filter(g => g.status === customFilter.value.status)

  if (!customPages[tabKey]) customPages[tabKey] = 1
  const start = (customPages[tabKey] - 1) * customPageSize.value
  return goods.slice(start, start + customPageSize.value)
}

// 新增商品弹窗
const editMode = ref(false)
const showAddDialog = ref(false)
// 新增商品弹窗自定义字段
const addForm = ref({
  code: '', name: '', images: [] as any[], price: 0, freight: 0, photoFee: 0, realCount: 1, category: '', brand: '', startTime: '', endTime: '', quantity: 1, desc: '', status: '上架', auditStatus: 'pending', batch: '',
  customFields: [] as Array<{ key: string, value: string }>
})

// 计算属性：是否为拍卖会平台
const isAuctionPlatform = computed(() => {
  const plat = customPlatforms.value.find(p => p.key === addTabKey)
  return plat?.type === 'auction'
})

// 是否显示批次字段
const showBatchField = ref(false)
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

function handleImageRemove(file: UploadFile) {
  addForm.value.images = addForm.value.images.filter(f => f.url !== file.url)
}
function handlePictureCardPreview(file: UploadFile) {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
function beforeImageUpload(file: File) {
  const reader = new FileReader()
  reader.onload = e => {
    addForm.value.images.push({ name: file.name, url: e.target?.result as string })
  }
  reader.readAsDataURL(file)
  return false // 阻止自动上传
}
function addCustomField() {
  addForm.value.customFields.push({ key: '', value: '' })
}
function removeCustomField(idx: number) {
  addForm.value.customFields.splice(idx, 1)
}
let addTabKey = ''
function onAdd(tabKey: string) {
  addTabKey = tabKey
  editMode.value = false
  Object.assign(addForm.value, { code: '', name: '', images: [], price: 0, freight: 0, photoFee: 0, realCount: 1, category: '', brand: '', startTime: '', endTime: '', quantity: 1, desc: '', status: '上架', auditStatus: 'pending', batch: '', customFields: [] })
  
  // 重置批次字段显示状态
  showBatchField.value = false
  
  showAddDialog.value = true
}
function onSaveConfirm() {
  if (!addForm.value.name) return ElMessage.warning('请输入商品名称')
  const plat = customPlatforms.value.find(p => p.key === addTabKey)
  if (!plat) return

  const productData = {
    ...addForm.value,
    mainImage: addForm.value.images.length > 0 ? addForm.value.images[0].url : '',
    images: addForm.value.images.map(img => img.url),
    customFields: JSON.parse(JSON.stringify(addForm.value.customFields)),
    priceHistory: [] // 新增时初始化
  }
  productData.auditStatus = 'pending';

  if (editMode.value) {
    const index = plat.goods.findIndex(g => g.code === addForm.value.code)
    if (index > -1) {
      const oldPrice = plat.goods[index].price
      if (oldPrice !== productData.price) {
        if (!plat.goods[index].priceHistory) {
          plat.goods[index].priceHistory = []
        }
        plat.goods[index].priceHistory.push({
          date: dayjs().format('YYYY-MM-DD HH:mm'),
          oldPrice,
          newPrice: productData.price,
          operator: '当前用户' // 在实际应用中应替换为真实用户名
        })
      }
      plat.goods[index] = { 
        ...plat.goods[index], 
        ...productData,
        platformType: plat.type || 'normal' // 保持平台类型
      }
    }
    ElMessage.success('编辑并提交审核成功')
  } else {
    plat.goods.unshift({ 
      ...productData, 
      code: 'NEW' + Date.now(),
      platformType: plat.type || 'normal' // 添加平台类型
    })
    ElMessage.success('新增并提交审核成功')
  }
  showAddDialog.value = false
}
// 批量上架/下架
const selection = ref<any[]>([])
function onSelectionChange(val: any[]) { selection.value = val }
function onBatchUp(tabKey: string) {
  if (!selection.value.length) return ElMessage.warning('请先选择商品')
  selection.value.forEach(item => {
    item.auditStatus = 'pending'
    item.applyStatus = '上架'
  })
  ElMessage.success('批量上架申请已提交审核')
}
function onBatchDown(tabKey: string) {
  if (!selection.value.length) return ElMessage.warning('请先选择商品')
  selection.value.forEach(item => {
    item.auditStatus = 'pending'
    item.applyStatus = '下架'
  })
  ElMessage.success('批量下架申请已提交审核')
}
// 批量导入弹窗内容调整
const showImportDialog = ref(false)
let importTabKey = ''
function onImport(tabKey: string) {
  importTabKey = tabKey
  showImportDialog.value = true
}
function downloadImportTemplate() {
  // 生成xlsx模板，增加主图字段
  const header = ['商品名称','主图','价格','运费','拍照费','实际件数','品目','品牌','开始时间','结束时间','数量','说明','状态','所属批次']
  const ws = XLSX.utils.aoa_to_sheet([header])
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '商品导入模板')
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([wbout], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = '商品导入模板.xlsx'
  a.click()
  URL.revokeObjectURL(url)
}
function beforeImportUpload(file: File) {
  // 模拟导入并提交审核
  const reader = new FileReader();
  reader.onload = (e) => {
    if (!e.target || !e.target.result) return;
    const data = new Uint8Array(e.target.result as ArrayBuffer);
    const workbook = XLSX.read(data, { type: 'array' });
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const json = XLSX.utils.sheet_to_json(worksheet);

    const plat = customPlatforms.value.find(p => p.key === importTabKey);
    if (plat) {
      json.forEach((row: any) => {
        plat.goods.unshift({
          code: 'IMPORT' + Date.now() + Math.random(),
          name: row['商品名称'] || '',
          mainImage: row['主图'] || '',
          price: row['价格'] || 0,
          freight: row['运费'] || 0,
          photoFee: row['拍照费'] || 0,
          realCount: row['实际件数'] || 1,
          category: row['品目'] || '',
          brand: row['品牌'] || '',
          startTime: row['开始时间'] ? dayjs(row['开始时间']).format('YYYY-MM-DD') : '',
          endTime: row['结束时间'] ? dayjs(row['结束时间']).format('YYYY-MM-DD') : '',
          quantity: row['数量'] || 1,
          desc: row['说明'] || '',
          status: row['状态'] || '下架',
          auditStatus: 'pending',
          batch: row['所属批次'] || '',
          platformType: plat.type || 'normal', // 添加平台类型
          images: [],
          priceHistory: [],
          customFields: []
        });
      });
      ElMessage.success(`成功导入${json.length}条商品，已提交审核`);
    }
  };
  reader.readAsArrayBuffer(file);

  showImportDialog.value = false
  return false // 阻止自动上传
}

// 价格历史
const showPriceHistoryDialog = ref(false)
const currentPriceHistory = ref<any[]>([])
function showPriceHistory(row: any) {
  currentPriceHistory.value = row.priceHistory || []
  showPriceHistoryDialog.value = true
}

// 新增商品弹窗批次下拉选项生成
const batchOptions = Array.from({ length: 13 }, (_, i) => dayjs().add(i, 'month').format('YYYY-MM'))

function onEdit(row: any, tabKey: string) {
  addTabKey = tabKey
  editMode.value = true
  addForm.value = JSON.parse(JSON.stringify(row))
  if (row.images && Array.isArray(row.images)) {
    addForm.value.images = row.images.map((url: string, index: number) => ({
      name: `image_${index}.png`,
      url: url
    }))
  } else {
    addForm.value.images = []
  }
  showAddDialog.value = true
}
function onDelete(row: any, tabKey: string) {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', { type: 'warning' }).then(() => {
    const plat = customPlatforms.value.find(p => p.key === tabKey)
    if (!plat) return
    plat.goods = plat.goods.filter(g => g.code !== row.code)
    ElMessage.success('删除成功')
  })
}

// 审核状态格式化
function formatAuditStatus(status: string) {
  switch (status) {
    case 'pending': return '待审核'
    case 'approved': return '已通过'
    case 'rejected': return '未通过'
    default: return ''
  }
}
function getAuditStatusType(status: string) {
  switch (status) {
    case 'pending': return 'warning'
    case 'approved': return 'success'
    case 'rejected': return 'danger'
    default: return 'info'
  }
}

// 主图悬浮轮播逻辑
const imageStates = reactive<{ [key: string]: { currentIndex: number, intervalId: any } }>({});
function handleMouseEnter(row: any) {
    const key = row.code || row.platformId;
    if (!row.images || row.images.length <= 1) return;

    imageStates[key] = {
        currentIndex: 0,
        intervalId: setInterval(() => {
            imageStates[key].currentIndex = (imageStates[key].currentIndex + 1) % row.images.length;
        }, 800)
    };
}
function handleMouseLeave(row: any) {
    const key = row.code || row.platformId;
    if (imageStates[key]) {
        clearInterval(imageStates[key].intervalId);
        delete imageStates[key];
    }
}
function getCurrentImage(row: any) {
    const key = row.code || row.platformId;
    if (imageStates[key] && row.images && row.images.length > 0) {
        return row.images[imageStates[key].currentIndex];
    }
    return row.mainImage;
}

// 获取图片预览列表
function getImagePreviewList(row: any) {
    const images = [];
    
    // 添加主图
    if (row.mainImage) {
        images.push(row.mainImage);
    }
    
    // 添加其他图片
    if (row.images && Array.isArray(row.images)) {
        row.images.forEach((img: any) => {
            const imgUrl = typeof img === 'string' ? img : img.url;
            if (imgUrl && imgUrl !== row.mainImage) {
                images.push(imgUrl);
            }
        });
    }
    
    // 如果没有图片，返回空数组
    return images.length > 0 ? images : [row.mainImage || ''];
}

// 获取平台类型名称
function getPlatformTypeName(type: string): string {
    const typeNames: Record<string, string> = {
        'normal': '普通商品',
        'auction': '拍卖会'
    }
    return typeNames[type] || '未知类型'
}

// 获取平台类型标签样式
function getPlatformTypeTagType(type: string): string {
    const tagTypes: Record<string, string> = {
        'normal': 'success',  // 绿色
        'auction': 'warning'  // 橙色
    }
    return tagTypes[type] || 'info'
}

// 处理图片点击事件
function handleImageClick(row: any) {
    const imageList = getImagePreviewList(row);
    if (imageList.length > 0) {
        // 触发图片预览
        console.log('图片预览列表:', imageList);
    }
}

// mock 商品列表
const productList = ref(Array.from({ length: 30 }, (_, i) => ({
  code: `P20240601${String(i + 1).padStart(3, '0')}`,
  name: `美白面膜${i + 1}`,
  mainImage: 'https://img.yzcdn.cn/vant/cat.jpeg',
  images: [
    'https://img.yzcdn.cn/vant/cat.jpeg',
    'https://img.yzcdn.cn/vant/cat2.jpeg',
    'https://img.yzcdn.cn/vant/cat3.jpeg'
  ],
  category: '美妆个护',
  brand: '资生堂',
  price: 99 + i,
  stock: 100 - i,
  skus: [
    { skuCode: `P20240601${String(i + 1).padStart(3, '0')}-01`, spec: '10片/盒', price: 99 + i, stock: 50 },
    { skuCode: `P20240601${String(i + 1).padStart(3, '0')}-02`, spec: '20片/盒', price: 188 + i, stock: 50 }
  ],
  desc: `<p>这是一款主打美白功效的面膜，适合所有肤质，深层补水，提亮肤色。</p><ul><li>日本进口</li><li>温和无刺激</li><li>适合日常护理</li></ul>`
})))

const detailVisible = ref(false)
const currentProduct = ref<any>(null)

function showDetail(row: any) {
  // 平台商品（tab.key === 'spider'）弹窗，其他平台跳转详情页
  if (activeTab.value === 'spider') {
    currentProduct.value = row
    detailVisible.value = true
  } else {
    // 暂时注释掉router跳转，因为router未定义
    // router.push(`/product/detail/${row.code}`)
    console.log('跳转到商品详情页:', row.code)
  }
}
</script>

<style scoped>
.table-toolbar {
  margin-bottom: 12px;
}
</style> 